package com.boyon.common.filter;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import com.boyon.common.status.Constant;
import com.boyon.web.interceptor.Filter;

import lombok.extern.slf4j.Slf4j;

/**
 * ClassName:AuthorityFilter <br/>
 * Function: 权限过滤器. <br/>
 * Date: 2018年3月19日 下午3:27:33 <br/>
 * 
 * @author sunshulin
 * @version
 * @since JDK 1.8
 * @see
 */
@Component
@Slf4j
public class AuthorityFilter implements Filter {

	private static final String REQUEST_AUTHORITY_CODE = "cdoe";

	private static final String AUTHORITY_FILTER = "boyon";

	private static final String[] UN_AUTHORITY_FILTER = {"boyon/index", "beyon"};
	private static final String EXCEPTION = "exception";

	/**
	 * 系统权限过滤取.
	 * 
	 * @see com.boyon.web.interceptor.Filter#preHandle(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse, java.lang.Object)
	 */
	@SuppressWarnings("unchecked")
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) {
		String uri = request.getRequestURI();
		String code = request.getParameter(REQUEST_AUTHORITY_CODE);
		log.debug("请求uri={}, code={}", uri, code);
		if (uri.contains(EXCEPTION)) {
			return true;
		}
		for (String unAuthority : UN_AUTHORITY_FILTER) {			
			if (uri.contains(unAuthority)) {
				return true;
			}
		}
		if (uri.contains(AUTHORITY_FILTER)) {
			List<String> menus = (List<String>) request.getSession()
					.getAttribute(Constant.SESSION_USER_AUTHORITY);
			if (menus.contains(code)) {
				return true;
			}
		}
		return true;
	}

	/**
	 * .
	 * 
	 * @see com.boyon.web.interceptor.Filter#postHandle(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
	 *      org.springframework.web.servlet.ModelAndView)
	 */
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) {

	}

	/**
	 * .
	 * 
	 * @see com.boyon.web.interceptor.Filter#afterCompletion(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
	 *      java.lang.Exception)
	 */
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {

	}

	/**
	 * 排序号.
	 * 
	 * @see com.boyon.web.interceptor.Filter#order()
	 */
	public int order() {
		return 1;
	}

}
